package com.mutual.common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.common.collect.Maps;
import com.mutual.attachment.pojo.Attachment;
import com.mutual.attachment.service.AttachmentService;
import com.mutual.commom.constant.GeneralConstant;
import com.mutual.commom.pojo.ReturnResult;
import com.mutual.commom.util.ReadXML;
import com.mutual.system.appUser.controller.AppUserController;

@Controller
public class FileUploadController extends BaseController {
	
	@Resource
	private AttachmentService attachmentService;
	
	private static Logger logger = Logger.getLogger (FileUploadController.class);
	
    private String img_pattern = ".jpg;.jpeg;.bmp;.png";
    private String file_pattern = ".doc;.docx;.ppt;.pptx;.xls;.xlsx;.txt;.pdf";

    /**
     * 处理图片上传
     * 
     * @param response
     * @param request
     * @return
     * @throws IOException
     * @throws ServiceException
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    public ReturnResult uploadImg(HttpServletResponse response, HttpServletRequest request) throws IOException,
            Exception {
        String result = "";
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 创建文件夹
        String real_path = ReadXML.readProperties("filePath.properties", "realFilePath");
        File file = new File(real_path);
        if (!file.exists()) {
            file.mkdirs();
        }
        ReturnResult returnResult=new ReturnResult();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            String fileName = mf.getOriginalFilename();// 获取原文件名
            String newfileName = getSaveFileName(fileName);// 获取存储的文件名
            if (!validateFileType(fileName, img_pattern)) {
                result = fileName + "图片后缀名不符合要求!只能上传" + img_pattern + "的后缀名!";
                returnResult.setReturnMsg(result);
                returnResult.setStatus(ReturnResult.STATUS_FAILED);
                return returnResult;
            }
            File uploadFile = new File(real_path + File.separator + newfileName);
            try {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                String dbFilePath = ReadXML.readProperties("filePath.properties", "dbFilePath") + newfileName;
                Attachment attachment=new Attachment();
                attachment.setTitle("产品图片");
                attachment.setType(Attachment.TYPE_PRODUCT);
                attachment.setHrefUrl(getBasePath()+dbFilePath);
                attachment.setPathInfo(dbFilePath);
                attachment.setRealPathInfo(real_path + File.separator + newfileName);
                attachmentService.insert(attachment);
                returnResult.setData(attachment.getId());
                returnResult.setReturnMsg("上传成功");
                returnResult.setStatus(ReturnResult.STATUS_SUCCESS);
                return returnResult;
            } catch (IOException e) {
            	logger.error("上传失败:", e);
            	 returnResult.setReturnMsg("上传失败");
                 returnResult.setStatus(ReturnResult.STATUS_FAILED);
            }
        }
        return returnResult;
    }

    /**
     * 处理文件上传
     * 
     * @param response
     * @param request
     * @return
     * @throws IOException
     * @throws ServiceException
     */
    @RequestMapping(value = "/uploadFile.action", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadFile(HttpServletResponse response, HttpServletRequest request) throws IOException,
            Exception {
        Map<String, Object> res = Maps.newHashMap();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 创建文件夹
        String real_path = "";
        File file = new File(real_path);
        if (!file.exists()) {
            file.mkdirs();
        }

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            String fileName = mf.getOriginalFilename();// 获取原文件名
            String newfileName = getSaveFileName(fileName);// //获取存储的文件名
            if (!validateFileType(fileName, file_pattern)) {
                res.put(GeneralConstant.SUCCESS, false);
                res.put("message", fileName + "文件后缀名不合法,只能上传" + file_pattern + "结尾的后缀名!");
                return res;
            }
            File uploadFile = new File(real_path + File.separator + newfileName);

            try {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                res.put(GeneralConstant.SUCCESS, true);
                res.put("dbpath", "" + newfileName);
            } catch (IOException e) {
                res.put(GeneralConstant.SUCCESS, false);
                throw new Exception(e);
            }
        }
        return res;

    }

    /**
     * 处理广告图片上传
     * 
     * @param response
     * @param request
     * @return
     * @throws IOException
     * @throws ServiceException
     */
    @RequestMapping(value = "/uploadAdImg.action", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadAdImg(HttpServletResponse response, HttpServletRequest request) throws IOException,
            Exception {
        Map<String, Object> res = Maps.newHashMap();
        res.put(GeneralConstant.SUCCESS, true);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String width = multipartRequest.getParameter("width");
        String height = multipartRequest.getParameter("height");
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 创建文件夹
        String real_path = "";
        File file = new File(real_path);
        if (!file.exists()) {
            file.mkdirs();
        }
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            String fileName = mf.getOriginalFilename();// 获取原文件名           
            String newfileName = getSaveFileName(fileName);// 获取存储的文件名
            if (!validateFileType(fileName, img_pattern)) {
                res.put(GeneralConstant.SUCCESS, false);
                res.put("message", fileName + "图片后缀名不符合要求!只能上传" + img_pattern + "的后缀名!");
                return res;
            }
            if("" != width && null != width && null != height && "" != height){
                res = validateImage(mf, width, height); // 校验像素
            }
            if((Boolean) res.get(GeneralConstant.SUCCESS)){
                File uploadFile = new File(real_path + File.separator + newfileName);
                try {
                    FileCopyUtils.copy(mf.getBytes(), uploadFile);
                    res.put(GeneralConstant.SUCCESS, true);
                } catch (IOException e) {
                    throw new Exception(e);
                } 
            }          
        }
        return res;
    }
    
    /**
     * 校验文件后缀名是否合法
     * 
     * @param filename
     * @param pattern
     * @return
     */
    private boolean validateFileType(String filename, String pattern) {
        String suffix = getSuffix(filename);
        if (pattern.contains(suffix)) {
            return true;
        }
        return false;
    }

    /**
     * 获取文件的后缀名
     * 
     * @param originFileName
     * @return
     */
    private String getSuffix(String originFileName) {
        return originFileName.substring(originFileName.lastIndexOf(".")).toLowerCase();
    }

    /**
     * 获取存储路径 /yyyyMMdd/xxxxx随机数
     * 
     * @return
     */
    private String getSavePath() {
        return new SimpleDateFormat("yyyyMMdd").format(new Date());
    }

    private String getSaveFileName(String originFileName) {
        return System.currentTimeMillis() + (Math.random() + "").replace(".", "").substring(0, 6)
                + getSuffix(originFileName);
    }
    
    private Map<String, Object> validateImage(MultipartFile editimage, String wdith_, String heigth_) throws IOException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put(GeneralConstant.SUCCESS, true);
        BufferedImage bi = ImageIO.read(editimage.getInputStream());
        double width = bi.getWidth(); // 像素
        double height = bi.getHeight(); // 像素
        StringBuffer sb = new StringBuffer();
        if (width > Double.parseDouble(wdith_)) {
            jsonMap.put(GeneralConstant.SUCCESS, false);
            sb.append("宽度不能超过" + wdith_ + "px");
        }
        if (height > Double.parseDouble(heigth_)) {
            jsonMap.put(GeneralConstant.SUCCESS, false);
            sb.append("高度不能超过" + heigth_ + "px");
        }
        jsonMap.put("success", sb.toString());
        return jsonMap;
    }
}
